package jpa.web.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.ws.rs.core.Context;

import jpa.entities.User;
import jpa.service.interfaces.UserManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping(value = "user")
public class UserController {
	private static Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserManager manager;

	public UserController() { 	}
	
	
	@RequestMapping(value = "/getList", method = RequestMethod.GET)
	@ResponseBody
	public List<User> getList(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		List<User> users = null;
		try {
			users = manager.findAllUsers();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}
	
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	@ResponseBody		
	public Long addUser(@Valid @ModelAttribute(value = "user") User user, BindingResult result) {
		long id = -1l;
		try {
			id = manager.insertUser(user); 
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return id;
	}
	

	@RequestMapping(value="/msgs/{msg}", method = RequestMethod.GET)
	@ResponseBody
	public String getMessage(HttpServletRequest request, @PathVariable String msg) {
		logger.debug(msg + "\n\n");
		
		return msg;
	}
}
